package com.evan.review.lifecycle;

import android.content.res.Configuration;
import android.os.Bundle;
import android.text.Editable;
import android.text.TextWatcher;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;

import androidx.annotation.NonNull;
import androidx.appcompat.app.AppCompatActivity;
import androidx.lifecycle.ViewModelProvider;

import com.evan.review.R;

/**
 * ViewModel演示Activity
 * 使用ViewModel在配置变更时保持数据状态
 */
public class ViewModelActivity extends AppCompatActivity {

    private static final String TAG = "ViewModelActivity";
    private TextView tvLifecycleInfo;
    private EditText etUserInput;
    private TextView tvInstanceInfo;
    private StringBuilder lifecycleLog = new StringBuilder();
    private int instanceCounter = 0;
    private static int totalInstances = 0;
    private LifecycleViewModel viewModel;
    
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_viewmodel);
        
        // 记录实例编号
        instanceCounter = ++totalInstances;
        
        // 获取ViewModel实例
        viewModel = new ViewModelProvider(this).get(LifecycleViewModel.class);
        
        // 从ViewModel恢复日志
        lifecycleLog = new StringBuilder(viewModel.getLifecycleLog());
        
        logLifecycleEvent("onCreate() - savedInstanceState: " + (savedInstanceState == null ? "null" : "not null") + " [实例#" + instanceCounter + "]");
        
        // 将最新日志保存到ViewModel
        viewModel.setLifecycleLog(lifecycleLog.toString());
        
        initViews();
        updateLifecycleInfo();
    }
    
    private void initViews() {
        tvLifecycleInfo = findViewById(R.id.tv_lifecycle_info);
        etUserInput = findViewById(R.id.et_user_input);
        tvInstanceInfo = findViewById(R.id.tv_instance_info);
        
        tvInstanceInfo.setText("当前实例: #" + instanceCounter + " / 总实例数: " + totalInstances);
        
        Button btnFinish = findViewById(R.id.btn_finish);
        btnFinish.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                finish();
            }
        });
        
        // 恢复用户输入并添加文本变化监听器
        etUserInput.setText(viewModel.getUserInput());
        etUserInput.addTextChangedListener(new TextWatcher() {
            @Override
            public void beforeTextChanged(CharSequence s, int start, int count, int after) {}
            
            @Override
            public void onTextChanged(CharSequence s, int start, int before, int count) {}
            
            @Override
            public void afterTextChanged(Editable s) {
                // 实时更新ViewModel中的用户输入
                viewModel.setUserInput(s.toString());
            }
        });
        
        // 使用TextView显示当前配置信息
        TextView tvConfig = findViewById(R.id.tv_current_config);
        updateConfigInfo(tvConfig);
        
        // 显示ViewModel状态
        TextView tvVMStatus = findViewById(R.id.tv_vm_status);
        updateViewModelStatus(tvVMStatus);
    }
    
    /**
     * 更新ViewModel状态显示
     */
    private void updateViewModelStatus(TextView tvStatus) {
        StringBuilder sb = new StringBuilder();
        sb.append("ViewModel实例哈希值: ").append(viewModel.hashCode()).append("\n");
        sb.append("已保存的文本长度: ").append(viewModel.getUserInput().length()).append(" 个字符\n");
        sb.append("已记录生命周期事件: ").append(countEvents()).append(" 条\n");
        sb.append("ViewModel会在Activity被完全销毁时一起销毁，而在配置变更时会被保留。");
        
        tvStatus.setText(sb.toString());
    }
    
    /**
     * 计算已记录的生命周期事件数量
     */
    private int countEvents() {
        String log = viewModel.getLifecycleLog();
        if (log == null || log.isEmpty()) {
            return 0;
        }
        return log.split("\n").length;
    }
    
    /**
     * 更新当前配置信息显示
     */
    private void updateConfigInfo(TextView tvConfig) {
        Configuration config = getResources().getConfiguration();
        String orientation = (config.orientation == Configuration.ORIENTATION_LANDSCAPE) ? "横屏" : "竖屏";
        int screenWidthDp = config.screenWidthDp;
        int screenHeightDp = config.screenHeightDp;
        float fontScale = config.fontScale;
        
        StringBuilder sb = new StringBuilder();
        sb.append("屏幕方向: ").append(orientation).append("\n");
        sb.append("屏幕宽度: ").append(screenWidthDp).append("dp\n");
        sb.append("屏幕高度: ").append(screenHeightDp).append("dp\n");
        sb.append("字体缩放: ").append(fontScale);
        
        tvConfig.setText(sb.toString());
    }
    
    /**
     * 记录生命周期事件
     */
    private void logLifecycleEvent(String event) {
        Log.d(TAG, event);
        lifecycleLog.append(event).append("\n");
        viewModel.setLifecycleLog(lifecycleLog.toString());
    }
    
    /**
     * 更新生命周期信息显示
     */
    private void updateLifecycleInfo() {
        tvLifecycleInfo.setText(lifecycleLog.toString());
        
        // 同时更新ViewModel状态显示
        TextView tvVMStatus = findViewById(R.id.tv_vm_status);
        updateViewModelStatus(tvVMStatus);
    }
    
    @Override
    protected void onStart() {
        super.onStart();
        logLifecycleEvent("onStart()");
        updateLifecycleInfo();
    }
    
    @Override
    protected void onResume() {
        super.onResume();
        logLifecycleEvent("onResume()");
        updateLifecycleInfo();
    }
    
    @Override
    protected void onPause() {
        super.onPause();
        logLifecycleEvent("onPause()");
        updateLifecycleInfo();
    }
    
    @Override
    protected void onStop() {
        super.onStop();
        logLifecycleEvent("onStop()");
    }
    
    @Override
    protected void onRestart() {
        super.onRestart();
        logLifecycleEvent("onRestart()");
        updateLifecycleInfo();
    }
    
    @Override
    protected void onDestroy() {
        super.onDestroy();
        logLifecycleEvent("onDestroy()");
    }
    
    @Override
    protected void onSaveInstanceState(@NonNull Bundle outState) {
        super.onSaveInstanceState(outState);
        logLifecycleEvent("onSaveInstanceState()");
        updateLifecycleInfo();
    }
    
    @Override
    protected void onRestoreInstanceState(@NonNull Bundle savedInstanceState) {
        super.onRestoreInstanceState(savedInstanceState);
        logLifecycleEvent("onRestoreInstanceState()");
        updateLifecycleInfo();
    }
} 